﻿using System;
using System.Collections.Generic;
using System.Linq;
using Configuration;
using Model;
using Repository.Common;

namespace Repository
{
    public class tkntImageRepository : Repository<tkntImage>
    {
        public tkntImageRepository(Database context)
            : base(context)
        {
        }

        public List<tkntImage> GetByProductId(int productId)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = from r in GetQuery().Include("Product").OrderBy(o => o.Id) where r.Product.Id == productId select r;

            return res.ToList();
        }

        public tkntImage GetByIdHaveProduct(int id)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = (from r in GetQuery().Include("Product").OrderBy(o => o.Id) where r.Id == id select r).SingleOrDefault();

            return res;
        }

        public int GetTotalPage(int productId, int numOfRows)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = from r in GetQuery().Include("Product").OrderBy(o => o.Id) where r.Product.Id == productId select r;

            return Convert.ToInt32((double)res.Count() / numOfRows) + 1;
        }

        public List<tkntImage> Paging(int productId, int pageIndex, int numOfRows)
        {
            var skipRows = (pageIndex - 1) * numOfRows;

            return GetByProductId(productId).Skip(skipRows).Take(numOfRows).ToList();
        }

        public string GetAvartar(int ProductID)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = (from r in GetQuery().OrderBy(o => o.Id) where r.Product.Id == ProductID && r.IsAvatar == true select r).FirstOrDefault();
            if (res != null)
                return res.Url;
            else
                return string.Empty;
        }
    }
}